package initialize

import (
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"github.com/opentracing/opentracing-go"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"mxshop_api/goods_web/global"
	"mxshop_api/goods_web/proto"
	"mxshop_api/goods_web/utils/otgrpc"
)

func InitSrvConn() {

	conn, err := grpc.Dial(fmt.Sprintf("consul://%s:%d/%s?wait=14s&tag=%s", global.WebConfig.Consul.Host, global.WebConfig.Consul.Port, global.WebConfig.Srv.Name, global.WebConfig.Srv.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer())),
	)

	if err != nil {
		zap.S().Fatal("连接【商品服务】失败")
	}
	//1. 后续的用户服务下线了 2. 改端口了 3. 改ip了 负载均衡来做
	//2. 已经事先创立好了连接，这样后续就不用进行再次tcp的三次握手
	//3. 一个连接多个groutine共用，性能 - 连接池
	global.RpcClient = proto.NewGoodsClient(conn)
}
